package com.sacfa.commons.connection;

import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.log4j.Logger;

/**
 * @author Leizar-Develop
 */
public class PoolConexion {
    private static PoolConexion instance = null;
    private BasicDataSource dataSource;
    
    private static Logger log = Logger.getLogger(PoolConexion.class);
    
    private PoolConexion() {
        dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://192.168.1.120:3306/sacfa");
        dataSource.setUsername("sacfauser");
        dataSource.setPassword("S4CF4");
        //User: AdminSACF4
        //Pass: sistemaSACFA
    }

    public static PoolConexion getInstance() {
        if(instance == null) {
            instance = new PoolConexion();
        }
        return instance;
    }

    public Connection getConexion() {
        Connection conex = null;
        try {
            conex = dataSource.getConnection();
        } catch (SQLException ex) {
            log.info("Error al hacer conexion: " + ex);
        }
        return conex;
    }

    public void endConection(Connection conexion) {
        try {
            if (conexion != null && !conexion.isClosed()) {
                conexion.close();
            }
        } catch (SQLException ex) {
            log.info("Error al cerrar la conexion: " + ex);
        }
    }
    
    public void beginTransaction(Connection conex) {
        try {
            if (conex != null && !conex.isClosed()) {
                conex.setAutoCommit(false);
            }
        } catch(SQLException ex) {
            log.info("Error al iniciar la transaccion: " + ex);
        }
    }

    public void endTransaction(Connection conex) {
        try {
            if (conex != null && !conex.isClosed()) {
                conex.setAutoCommit(true);
            }
        } catch(SQLException ex) {
            log.info("Error al finalizar la transaccion: " + ex);
        }
    }

    public void commit(Connection conex) {
        try {
            if (conex != null && !conex.isClosed()) {
                conex.commit();
            }
        } catch(SQLException ex) {
            log.info("Error al realizar el commit de la transaccion: " + ex);
        }
    }

    public void rollback(Connection conex) {
        try {
            if (conex != null && !conex.isClosed()) {
                conex.rollback();
            }
        } catch(SQLException ex) {
            log.info("Error al realizar el rollback de la transaccion: " + ex);
        }
    }
}